package org.xs.web.http;

import java.io.IOException;

import org.xs.web.http.provider.HTTPHeader;
import org.xs.web.http.provider.HTTPResponse;
import org.xs.web.util.Helpers;

public class JsonResponse implements XSResponse{

	private String contentType;
	private Object json;
	private int code;
	private HTTPHeader[] headers;
	
	public JsonResponse(Object json,int code ,String contentType,HTTPHeader[] headers){
		this.json = json;
		this.contentType = contentType;
		this.headers = headers;
		this.code = code;
	}
	
	public JsonResponse(Object json,String contentType,HTTPHeader[] headers){
		this(json,200,contentType,headers);
	}
	
	public JsonResponse(Object json ,HTTPHeader[] headers){
		this(json,200,"text/plain; charset=utf-8",headers);
	}
	
	public JsonResponse(Object json){
		this(json,200,"text/plain; charset=utf-8",new HTTPHeader[]{});
	}
	
	public JsonResponse(Object json,int code){
		this(json,code,"text/plain; charset=utf-8",new HTTPHeader[]{});
	}
	
	public JsonResponse(Object json,int code,HTTPHeader[] headers){
		this(json,200,"text/plain; charset=utf-8",headers);
	}
	
	@Override
	public int getCode() {
		return code;
	}

	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public HTTPHeader[] getHeaders() {
		return headers;
	}

	@Override
	public boolean isJs() {
		return true;
	}

	@Override
	public boolean isStream() {
		return false;
	}

	@Override
	public boolean isTemplete() {
		return false;
	}

	@Override
	public boolean isText() {
		return false;
	}

	@Override
	public boolean isXml() {
		return false;
	}

	@Override
	public Object apply(HTTPResponse response) {
		String text = Helpers.toJson(json);
		response.addHeader(XSRules.defaultHeaders());
		response.addHeader(headers);
		response.addHeader("Content-Length", String.format("%s", new Object[]{text.getBytes().length}));
		response.addHeader("Content-Type", contentType);
		response.setStatus(code);
		try {
			response.getDelegate().getWriter().write(text);
		} catch (IOException e) {

		}
		return true;
	}
 

}
